package cn.tworice.ip.security;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 域名安全检测
 * @author 二饭 [2023/3/7]
 **/
public class DomainSecurity {
    /**
     * 域名劫持检测
     * @param domain 待检测域名
     * @return boolean 为true时安全，为false时不安全
     * @author 二饭 [2023/3/7]
     **/
    public boolean security(String domain) {
        String[] dnsServers = {"8.8.8.8", "114.114.114.114"}; // DNS服务器地址

        try {
            // 获取域名的解析记录
            InetAddress[] resolvedAddresses = InetAddress.getAllByName(domain);

            // 检查域名的解析记录和DNS服务器的解析记录是否一致
            for (String dnsServer : dnsServers) {
                InetAddress[] dnsAddresses = InetAddress.getAllByName(dnsServer);
                if (!containsSameAddresses(resolvedAddresses, dnsAddresses)) {
                    return false;
                }
            }
            return true;
        } catch (UnknownHostException e) {
            System.out.println("获取域名解析记录失败，" + e.getMessage());
            return false;
        }
    }

    /**
     * 判断两个InetAddress数组是否包含相同的IP地址
     * @param addresses1 IP地址数组
     * @param addresses2 IP地址数组
     * @return boolean
     * @author 二饭 [2023/3/7]
     **/
    private boolean containsSameAddresses(InetAddress[] addresses1, InetAddress[] addresses2) {
        if (addresses1.length != addresses2.length) {
            return false;
        }
        for (InetAddress address1 : addresses1) {
            boolean contains = false;
            for (InetAddress address2 : addresses2) {
                if (address1.equals(address2)) {
                    contains = true;
                    break;
                }
            }
            if (!contains) {
                return false;
            }
        }
        return true;
    }
}
